package com.webull.information.center.carwler.task;

import java.util.List;
import java.util.function.Consumer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import com.webull.information.center.carwler.common.model.StockTitle;
import com.webull.information.center.carwler.task.handler.StockCNBCNewsHandler;
import com.webull.securities.client.model.Fund;
import com.webull.securities.client.model.Stock2Information;
import com.webull.securities.client.model.parm.FundNewsParam;
import com.webull.securities.client.service.FundService;
import com.webull.securities.client.service.StockService;

@Component
public class News_CNBC_UsStock_Task {
    protected final Logger logger = LogManager.getLogger(getClass());

    private @Autowired
    StockService stockService;
    private @Autowired
    FundService fundService;

    private @Autowired
    StockCNBCNewsHandler stockCNBCNewsHandler;
    private final Integer pageSize = 100;
    private @Autowired
    @Qualifier("executor_news")
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 全量扫描
     *
     * @since 0.1.0
     */
    public Integer stockFinanceNewsExchangeCode(String exchangeCode) {
        return stockFinanceNewsExchangeCode(exchangeCode, -1, null);
    }

    public Integer stockFinanceNewsExchangeCode(String exchangeCode, Integer lastId, Integer loop) {
        logger.info("News_CNBC_UsStock_Task.News_CNBC_UsStock_TaskExchangeCode start exchangeCode:{},lastId:{},loop:{}",
                exchangeCode, lastId, loop);
        int loop_ = 0;
        full:
        do {
            if (loop != null && loop > 0 && ++loop_ > loop) {
                break full;
            }
            List<Stock2Information> res = stockService.queryPagingInform(exchangeCode, lastId, pageSize);
            if (res == null || res.isEmpty()) {
                lastId = null;
                break full;
            }
            logger.info("News_CNBC_UsStock_Task.News_CNBC_UsStock_TaskExchangeCode stocks:" + res.size());
            lastId = res.get(res.size() - 1).getTickerId();
            procss(res);
        } while (true);

        return lastId;
    }


    public Integer etfFinanceNewsExchangeId(Integer regionId) {
        return etfFinanceNewsExchangeId(regionId, -1, null);
    }

    public Integer etfFinanceNewsExchangeId(Integer regionId, Integer lastId, Integer loop) {
        logger.info("News_CNBC_UsETF_Task.News_CNBC_UsStock_TaskExchangeCode start regionId:{},lastId:{},loop:{}",
                regionId, lastId, loop);
        int loop_ = 0;
        full:
        do {
            FundNewsParam param = new FundNewsParam();
            param.setRegionId(regionId);
            param.setSpecialType(Fund.SpecialTypeConstants.ETFFUND);
            List<Fund> res = fundService.queryPagingByParm(param, lastId, pageSize);
            if (res == null || res.isEmpty()) {
                lastId = null;
                break full;
            }
            logger.info("News_GoogleFull_EtfFund_Task.News_GoogleFull_EtfFund_TaskExchangeCode stocks:" + res.size());
            lastId = res.get(res.size() - 1).getTickerId();
            procssEtfs(res);
        } while (true);

        return lastId;
    }

    private void procssEtfs(List<Fund> res) {

        if (res == null)
            return;
        /**
         * 网站有请求过滤？
         */
        for (int i = 0; i < res.size(); i++) {
            try {
                etfProcess.accept(res.get(i));
            } catch (Exception e) {
                logger.error("News_CNBC_UsETF_TaskTask 全量新闻任务失败", e);
            }
        }
//			News_TaskUtil.multiThreadProcess(res, process, threadPoolTaskExecutor);
        logger.info("News_CNBC_UsETF_TaskTask procss end:" + res.size());
    }

    private void procss(List<Stock2Information> res) {
        if (res == null)
            return;
        /**
         * 网站有请求过滤？
         */
        for (int i = 0; i < res.size(); i++) {
            try {
                process.accept(res.get(i));
            } catch (Exception e) {
                logger.error("News_CNBC_UsStock_TaskTask 全量新闻任务失败", e);
            }
        }
//			News_TaskUtil.multiThreadProcess(res, process, threadPoolTaskExecutor);

        logger.info("News_CNBC_UsStock_TaskTask procss end:" + res.size());

    }

    private final Consumer<Stock2Information> process = input -> {
        StockTitle stockTitle = new StockTitle();
        BeanUtils.copyProperties(input, stockTitle);
		stockTitle.setCfgSource("cnbc_en");
		stockCNBCNewsHandler.handlerByStockTitle4CNBC(stockTitle);
        logger.info("News_CNBC_UsStock_Task.procss stockTitle:" + stockTitle);
    };

    private final Consumer<Fund> etfProcess = input -> {
        StockTitle stockTitle = new StockTitle();
        BeanUtils.copyProperties(input, stockTitle);
		stockTitle.setCfgSource("cnbc_etf");
		stockCNBCNewsHandler.handlerByStockTitle4CNBC(stockTitle);
        logger.info("News_CNBC_UsStock_Task.procss stockTitle:" + stockTitle);
    };

}
